/**
 * demo全局变量
 */
import {
  externalList,
  addExternal,
  editExternal,
  listItemDetail,
  removeExternal,
} from '@/services/demo';

const Demo = {
  // 调用 model 的时候，通过命名空间调用，不要和其他的 model 同名
  namespace: 'demo',

  // 状态，跟 react 中的 state 类似，和 redux 中保存的 state 一样
  state: {
    currentPage: 1, // 列表当前页
    pageSize: 50, // 列表每页数目
    total: 0, // 列表总数目
  },

  // 调用服务器接口，获取数据
  effects: {
    // 列表
    *fetchGetList({ payload, callback }, { call, put, select }) {
      const state = yield select((state) => {
        const { currentPage, pageSize } = state.demo;
        return { currentPage, pageSize };
      });
      const response = yield call(externalList, { ...payload, ...state });
      callback && callback(response);
      return response;
    },
    // 新增
    *fetchAdd({ payload, callback }, { call }) {
      const response = yield call(addExternal, payload);
      callback && callback(response);
      return response;
    },
    // 编辑
    *fetchEdit({ payload, callback }, { call }) {
      const response = yield call(editExternal, payload);
      callback && callback(response);
      return response;
    },
    // 删除
    *fetchRemove({ payload, callback }, { call }) {
      const response = yield call(removeExternal, payload);
      callback && callback(response);
      return response;
    },
    // 单条详情
    *fetchListItemDetail({ payload, callback }, { call }) {
      const response = yield call(listItemDetail, payload);
      callback && callback(response);
      return response;
    },
  },

  // 更新 state
  reducers: {
    saveDatas(state, action) {
      const keys = Object.keys(action.payload);
      const newDatas = {};
      keys.forEach((key) => {
        newDatas[key] = action.payload[key];
      });
      return {
        ...state,
        ...newDatas,
      };
    },
  },
};

export default Demo;
